import sleepDataService from '../services/sleepData.js';
import Result from '../utils/result.js';

const sleepDataController = {
    async getLatestSleepData(req, res) {
        const { userId } = req.params;

        try {
            const result = await sleepDataService.getLatestSleepData(userId);

            if (result.code !== 200) {
                return res.status(result.code).json(result.toObject());
            }

            return res.status(200).json(result.toObject());
        } catch (error) {
            return res.status(500).json(Result.error(error.message).toObject());
        }
    },
    async getSleepHistory(req, res) {
        const { userId } = req.params;
        const { startDate, endDate } = req.query;

        try {
            // 如果没有传递 startDate 和 endDate，则默认取出全部数据
            if (!startDate && !endDate) {
                const result = await sleepDataService.getSleepHistory(userId);
                if (result.code !== 200) {
                    return res.status(result.code).json(result.toObject());
                }
                return res.status(200).json(result.toObject());
            } else {
                const result = await sleepDataService.getSleepHistory(userId, startDate, endDate);
                if (result.code !== 200) {
                    return res.status(result.code).json(result.toObject());
                }
                return res.status(200).json(result.toObject());
            }
        } catch (error) {
            return res.status(500).json(Result.error(error.message).toObject());
        }
    },
    async getSleepStatistics(req, res) {
        const { userId } = req.params;
        const { period } = req.query;

        try {
            const result = await sleepDataService.getSleepStatistics(userId, period);

            if (result.code !== 200) {
                return res.status(result.code).json(result.toObject());
            }

            return res.status(200).json(result.toObject());
        } catch (error) {
            return res.status(500).json(Result.error(error.message).toObject());
        }
    }
};
export default sleepDataController;
